<?php
namespace Hilaoyu\Utils;

use Hilaoyu\Utils\Traits\ErrorsTrait;


/**
 * Created by laoyu.
 * User: hilaoyu@qq.com
 * Date: 2018/3/8
 * Time: 9:45
 *
 *
 */
class Sms {

    use ErrorsTrait;
    protected $driver = null;

    static protected $statics = [];

    /**
     * @param string $driver_name
     * @param array $config
     * @return static
     */
    static public function make($driver_name,$config){
        $driver_name = trim($driver_name);

        if(!isset(static::$statics[$driver_name])){
            static::$statics[$driver_name] = new static($driver_name,$config);
        }

        return static::$statics[$driver_name];
    }

    public function __construct($driver_name,$config=[])
    {

        $this->createDriver($driver_name,$config);
    }

    public function createDriver($driver_name,$config=[]){
        $driver_name = __NAMESPACE__ .'\\Drivers\\Sms\\'.UtilStr::ucFirst(trim($driver_name));

        $this->driver = UtilSupport::makeClass($driver_name,$config);

    }

    public function send($phone,$content,$tpl=""){
        try{
            if($this->driver->send($phone,$content,$tpl)){
                return true;
            }
            $this->setError($this->driver->getError());
        }catch (\Exception $exception){
            $this->setError($exception->getMessage());
        }
        return false;
    }

    public function sendBatch(array $phones,$content,$tpl=""){
        try{
            if($this->driver->sendBatch($phones,$content,$tpl)){
                if ($this->driver->getError()){
                    $this->setError($this->driver->getError());
                }
                return true;
            }
            $this->setError($this->driver->getError());
        }catch (\Exception $exception){
            $this->setError($exception->getMessage());
        }
        return false;
    }


}
